﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using Medianamik.Core.Sugar;
using Roles = Medianamik.Core.Security.Roles;
using Medianamik.Core.Security;
using Medianamik.Core;
using Medianamik.Globalization;

namespace Medianamik.UI.SecurityManagement
{
    public partial class GroupManagement : BasePage
    {
        private const string ParentGroupIdParamName = "basetypeid";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (IsNew)
                {
                    if (ParentGroup == null || !MedianamikUser.CanEditChildGroups(ParentGroup))
                    {
                        Response.Redirect(ReturnURL);
                    }
                }
                else
                {
                    if (CurrentGroup == null || !MedianamikUser.CanEditGroup(CurrentGroup))
                    {
                        Response.Redirect(ReturnURL);
                    }
                }

                BindControls();
            }
        }

        protected void cvGroupName_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (string.IsNullOrEmpty(args.Value))
            {
                args.IsValid = false;
                cvGroupName.ErrorMessage = Resources("Medianamik_SecurityManagement",
                    "ErrorEmptyGroupName");
            }
            else if (Roles.GroupExists(args.Value))
            {
                args.IsValid = false;
                cvGroupName.ErrorMessage = Resources("Medianamik_SecurityManagement",
                    "ErrorGroupAlreadyExists");
            }
            else
            {
                args.IsValid = true;
            }
        }

        protected void Save_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string groupName;
                var logger = new Core.Logging.ActivityLogger();
                string message;

                if (IsNew)
                {
                    groupName = txtGroupName.Text;
                    Roles.CreateGroup(groupName, ParentGroup.ID);
                    message = "Group Created";
                }
                else
                {
                    groupName = CurrentGroup.Name;
                    message = "Group Modified";
                }

                logger.Log(new Core.Logging.LoggableObject(groupName, Core.Logging.LogEntryType.Group), message);

                var selectedRoles = chkRoles.Items.Cast<ListItem>()
                    .Where(i => i.Selected).Select(i => i.Value);

                var notSelectedRoles = chkRoles.Items.Cast<ListItem>()
                    .Select(i => i.Value).Except(selectedRoles);

                Roles.RemoveRolesFromGroup(notSelectedRoles.ToArray(), groupName);
                Roles.AddRolesToGroup(selectedRoles.ToArray(), groupName);

                Translator.CreateResource("Medianamik_SecurityManagement", "Group_" + groupName, GroupTranslator.Values);

                Response.Redirect(ReturnURL);
            }
        }

        private void BindControls()
        {
            if (IsNew)
            {
                GroupNamePlaceHolder.Visible = true;
            }
            else
            {
                GroupNamePlaceHolder.Visible = false;
                chkRoles.SelectedRoles = Roles.GetRolesInGroup(CurrentGroup.Name);
                GroupTranslator.Values = Translator.GetResources("Medianamik_SecurityManagement",
                    "Group_" + CurrentGroup.Name, ConfigManager.GetMedianamikCultures().Select(c => c.CultureInfo));
            }

            chkRoles.DataBind();

            for (int i = 0; i < chkRoles.Items.Count; i++)
            {
                var roleListItem = chkRoles.Items[i];
                roleListItem.Enabled = Roles.IsUserInRole(roleListItem.Value);
            }
        }

        protected bool IsNew
        {
            get { return CurrentGroup == null; }
        }

        protected string ReturnURL
        {
            get
            {
                var returnURL = "GroupList.aspx";

                if(IsNew)
                    returnURL += "?basetypeid=" + ParentGroup.ID;
                else if (CurrentGroup.ParentID.HasValue)
                    returnURL += "?basetypeid=" + CurrentGroup.ParentID.Value;

                return returnURL;
            }
        }

        private Group _group;
        protected Group CurrentGroup
        {
            get
            {
                var groupName = Request["name"] ?? string.Empty;

                if (_group == null && groupName != String.Empty)
                {
                    _group = SecurityManager.GetGroup(groupName);
                }

                return _group;
            }
        }

        protected Guid? GetParentGroupId()
        {
            return GetQueryStringValue<Guid?>(ParentGroupIdParamName);
        }

        private Group _parentGroup;
        protected Group ParentGroup
        {
            get
            {
                var parentGroupId = GetParentGroupId();

                if (parentGroupId.HasValue && _parentGroup == null)
                {
                    _parentGroup = SecurityManager.GetGroup(parentGroupId.Value);
                }

                return _parentGroup;
            }
        }
    }
}
